//
//  WordsView.m
//  LineByLine
//
//  Created by 병철 김 on 11. 10. 25..
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "WordsView.h"
#import "WordManager.h"
#import "CommonDefine.h"
#import "WordButton.h"


#define kPosY 110
#define kFontSize 16.0
#define kFontMargin 8
#define kLineHeight 38
#define kFontPadding 20
#define kFontHeight 30
#define kIncorrentLimit 3

@implementation WordsView
@synthesize sentence, viewDelegate;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor blueColor]];
        wordViews = [[NSMutableArray alloc] initWithCapacity:30];
        
        resultView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, kContentWidth, 100)];
        [resultView setFont:[UIFont systemFontOfSize:16]];
        [resultView setEditable:NO];
        
        [self addSubview:resultView];
        [resultView release];
    }
    return self;
}

- (void) removeWordViews {
    for (UIView *view in wordViews) {
        [view removeFromSuperview];
    }
    [wordViews removeAllObjects];
}

- (void) initViewData {
    [self removeWordViews];
    [resultView setText:@""];
    currentWordPos = 0;
    incorrectCount = 0;
    
    if (_wordsFinishView) {
        [_wordsFinishView hide];
    }
}

- (void) createWordButton:(CGSize)fontSize posy:(float)posy margin:(float)margin posx:(float)posx word:(NSString *)word font:(UIFont *)font {
    WordButton *wordButton = [[WordButton alloc] initWithFrame:CGRectMake(posx + margin, posy, fontSize.width + kFontPadding, kFontHeight)];
    [wordButton setWord:word];
    [wordButton setFont:font];
    [wordButton setTarget:self action:@selector(onClickWordView:)];
    [wordButton configView];
    [self addSubview:wordButton];
    [wordViews addObject:wordButton];
}

- (NSMutableArray*) shuffleWords {
    NSMutableArray *shuffledWords = [words mutableCopy];
    
    for (int i=0; i<[shuffledWords count]; i++) {
        int index = arc4random() % [shuffledWords count];
        id object = [shuffledWords objectAtIndex:index];
        [shuffledWords removeObjectAtIndex:index];
        [shuffledWords insertObject:object atIndex:i];
    }
    
    return shuffledWords;
}

- (void) configView {
    [self initViewData];
    
    words = [[WordManager splitWords:[sentence valueForKey:@"a"] language:kLanguageEN] retain];
    NSArray *shuffledWords = [self shuffleWords];
    
    UIFont *font = [UIFont boldSystemFontOfSize:kFontSize];
    
    float posx = 0;
    float posy = kPosY;
    float margin = kFontMargin;
    for (int i=0; i<[shuffledWords count]; i++) {
        NSString *word = [shuffledWords objectAtIndex:i];
        
        CGSize fontSize = [word sizeWithFont:font];
        if ((posx + fontSize.width + kFontPadding + margin) > self.frame.size.width) {
            posy += kLineHeight;
            posx = 0;
        }
        
        [self createWordButton:fontSize posy:posy margin:margin posx:posx word:word font:font];
        
        posx += (fontSize.width + kFontPadding + margin);
    }
}

- (BOOL) isCorrectWord:(NSString*) word {
    NSString *rightWord = [words objectAtIndex:currentWordPos];
    return [rightWord isEqualToString:word];
}

- (void) assist {
    NSString *rightWord = [words objectAtIndex:currentWordPos];
    
    for (WordButton *wordButton in wordViews) {
        if ([wordButton isEqualWord:rightWord]) {
            [wordButton assistWordButton];
            break;
        }
    }
}

- (WordsFinishView*) wordsFinishView {
    if (!_wordsFinishView) {
        _wordsFinishView = [[WordsFinishView alloc] initWithFrame:CGRectMake(0, -76, 320, 176)];
        [self addSubview:_wordsFinishView];
        [self sendSubviewToBack:_wordsFinishView];
        [_wordsFinishView release];
    }
    return _wordsFinishView;
}


#pragma mark - event handler
- (void) onClickWordView:(WordButton*) wordView {
    NSString *word = [wordView word];
    if ([self isCorrectWord:word]) {
        incorrectCount = 0;
        currentWordPos++;
        [wordView removeFromSuperview];
        [wordViews removeObject:wordView];
        
        [resultView setText:[NSString stringWithFormat:@"%@ %@", resultView.text, word]];
        
        if ([wordViews count] == 0) {
            NSTimeInterval timeInterval = [viewDelegate didFinishSentence:sentence];
            WordsFinishView *wordFinishView = [self wordsFinishView];
            [wordFinishView setTimeInterval:timeInterval];
            [wordFinishView configView];
            [wordFinishView show];
        }
    } else {
        incorrectCount++;
        if (incorrectCount >= kIncorrentLimit) {
            [self assist];
        }
    }
}

- (void)dealloc {
    [wordViews release];
    [words release];
    [sentence release];
    [super dealloc];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {}
@end
